package main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import model.Board;
import model.Move;
import controller.Game;
import controller.IllegalPositionException;

public class Main {
	static Game game = new Game();
	/**
	 * @param args
	 */
	static int[] pos = new int[3];
	public static void main(String[] args) {
	
		
		while(!game.isFinished()){
			System.out.println(game.toString());
			System.out.println("aktive: "+game.getCurrentPlayer().getColor()+" "+game.getMove());
			try {
				readPosition();
				if(game.getMove() == Move.Remove){
					game.removeStone(pos[0], pos[1], pos[2]);
				}else{
					if(game.getMove() == Move.Set){
						game.setStone(pos[0], pos[1], pos[2]);
					}else{
						game.removeStone(pos[0], pos[1], pos[2]);
						game.setMove(Move.Set);
					}
				}
					
			} catch (IllegalPositionException e) {
				System.err.println("illigal Move");
				e.printStackTrace();
				continue;
			}
			
		}
		System.out.println("That's all folks!!");
	}

	private static void readPosition() throws IllegalPositionException {
		String text = null;
		boolean inputOK = false;
		char[] cArray = null;
		while(!inputOK){
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
				text = reader.readLine();
				   
			} catch (IOException e) {
			   e.printStackTrace();
			}
				//return text;
			cArray = text.toCharArray();
			
			if(cArray.length > 3){
				System.err.println("Illigal input.");
				continue;
			}else{
				if(((Board) game.getBoard()).checkPosition(getInt(cArray[0]),getInt(cArray[1]),getInt(cArray[2]))){
					inputOK = true;
					continue;
				}
			}
		}	
		if(inputOK){
			pos[0] = getInt(cArray[0]);
			pos[1] = getInt(cArray[1]);
			pos[2] = getInt(cArray[2]);
		}
		System.out.println("Eingabe:"+pos[0]+pos[1]+pos[2]);
	}

	private static int getInt(char c) {
		switch(c){
		case '0': return 0;
		case '1': return 1;
		case '2': return 2;
		}
		return -1;
	}	
}
